package io.libp2p.example.chat;

import android.content.Context;
import android.util.Base64;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileRecv {
    String fileId;

    String path;

    String fileName;

    long fileSize;

    FileOutputStream fos;

    long recvSize;

    long startTime;

    long lastAddTime;

    int progress;

    float speedCur;

    long speedAvg;

    public FileRecv(Context context, String fileId, String fileName, long fileSize) throws FileNotFoundException {
        this.fileId = fileId;
        this.fileName = fileName;
        this.fileSize = fileSize;

        String dir = context.getExternalCacheDir().getAbsolutePath() + "/"+ fileId + "/"+fileName;

        new File(dir).mkdirs();

        path = dir + "/"+fileName;

        fos = new FileOutputStream(path);

        startTime = System.currentTimeMillis();
        lastAddTime = startTime;
    }

    public FileRecv( String fileId, String fileName, long fileSize, String path) throws FileNotFoundException {
        this.fileId = fileId;
        this.fileName = fileName;
        this.fileSize = fileSize;
        this.path = path;

        startTime = System.currentTimeMillis();
        lastAddTime = startTime;
    }

    public void addData(String base64) throws IOException {
        byte[] buf = Base64.decode(base64, Base64.DEFAULT);

        if(fos != null) fos.write(buf);

        recvSize += buf.length;

        lastAddTime = System.currentTimeMillis();

        progress = Math.round(recvSize*100f/fileSize);

        //LibP2pLog.D("addData size = "+recvSize+"/"+fileSize);

        speedAvg = recvSize*1000/(System.currentTimeMillis() - startTime);
    }

    public void endRecv() throws IOException {
        if(fos != null) fos.close();
        progress = 100;
        recvSize = fileSize;
    }

    public void clear(){
        try {
            new File(path).delete();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public String getFileSizeString(){
        return formatFileSize(fileSize);
    }

    public String getSpeedAvgString(){
        return formatFileSize(speedAvg)+"/s";
    }

    public boolean isComplete(){
        return fileSize == recvSize;
    }

    public static String formatFileSize(long sizeBytes) {
        if (sizeBytes < 0) {
            throw new IllegalArgumentException("文件大小不能为负数");
        }

        String[] units = {"B", "KB", "MB", "GB", "TB"};
        int unitIndex = 0;
        double size = sizeBytes;

        // 循环计算合适的单位
        while (size >= 1024 && unitIndex < units.length - 1) {
            size /= 1024;
            unitIndex++;
        }

        // 根据单位选择格式化方式
        String formatPattern;
        if (unitIndex == 0) {
            // B 单位不显示小数
            return String.format("%d %s", (long) size, units[unitIndex]);
        } else if (size < 10) {
            // 小于10时保留2位小数（例如：1.23 MB）
            formatPattern = "%.2f %s";
        } else if (size < 100) {
            // 小于100时保留1位小数（例如：12.3 MB）
            formatPattern = "%.1f %s";
        } else {
            // 大于等于100时保留整数（例如：123 MB）
            formatPattern = "%.0f %s";
        }

        return String.format(formatPattern, size, units[unitIndex]);
    }

}
